package org.itboys.mobile.service.mongo.weixin;


import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.ZhongBaoContact;
import org.itboys.mobile.service.mongo.mobile.SundayMobileCodeService;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_用户_service
 */
@Service
public class SundayWeiXinMemberService extends BaseMongoService<SundayMember> {

    @Autowired
    private SundayMobileCodeService codeService;
    @Autowired
    protected ResourceHolder resourceHolder;
    @Autowired
    private ZhongBaoWeiXinTagService tagService;



    @Resource(name = "mobileDs")
    private MongoDataSource kitchenDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return kitchenDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }

    /**
     * 根据条件查询用户
     * @param request
     * @param userType
     * @param parentId
     * @param nickName
     * @return
     */
    public List<SundayMember> getMembers(HttpServletRequest request,Integer userType,Long parentId,String nickName,List<Long> memberIds,List<Long> notMemberIds){
        Map<String,Object> param = new HashMap<String ,Object>();
        param.put("isDeleted",0);
        if(userType!=null){
            param.put("userType",userType);
        }
        if(LongUtil.isNotZreo(parentId)){
            //如果本身自己就是员工
           SundayMember member =super.getById(parentId);
           if(LongUtil.isNotZreo(member.getParentId())){
               param.put("parentId",member.getParentId());
           }else{
               param.put("parentId",parentId);
           }

        }
        if(StringUtils.isNotEmpty(nickName)){
            param.put("contains:nickName",nickName);
        }
        if(ListUtil.isNotNull(memberIds)){
            param.put("id in",memberIds);
        }
        String imgRoot = resourceHolder.getStringValue("imgRoot");
        List<SundayMember> members = super.list(param);
        for(SundayMember member:members){
            member.setImage(imgRoot+member.getImage());
        }
        return members;

    }


    /**
     * 个人或企业注册（实际已经根据微信授权，生成了用户，这一步是完善个人信息）。企业和个人。不更改用户类型
     * @param memberId
     * @param code
     * @param nickName
     * @param mobile
     * @param trade
     * @param career
     * @param provinceId
     * @param provinceName
     * @param cityId
     * @param cityName
     * @param districtId
     * @param districtName
     * @return
     */
    public void register(HttpServletRequest request,Long memberId,String code,String nickName,String mobile,String trade,String career,
                                     Long provinceId, String provinceName, Long cityId, String cityName, Long districtId, String districtName,String company,String mobileName,Integer userType){
        //检验验证码
       int reulct_code =codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_register);
        if(reulct_code!=0){
            throw new ErrorException("验证码错误");
        }
        SundayMember member = new SundayMember();
        member.setId(memberId);
        member.setNickName(nickName);
        member.setMobile(mobile);
        member.setTrade(trade);
        member.setCareer(career);
        member.setProvinceId(provinceId);
        member.setProvinceName(provinceName);
        member.setCityId(cityId);
        member.setCityName(cityName);
        member.setDistrictId(districtId);
        member.setDistrictName(districtName);
        member.setCompany(company);
        //2017年11月18日，支付时才变更用户类型
      //  member.setUserType(userType);
        member.setStatus(SundayCommonConstants.user_status_dxf);
        super.updateExceptEmpty(memberId,member);
        //重新把用户放入session中
        insertMemberToSession(request, memberId, null);

    }


    /**
     * 将用户转换DTO保存到sesssion中。微信专用
     * @param request
     * @param memberId
     * @param memberSessionDto
     */
    public SundayMemberSessionDto insertMemberToSession(HttpServletRequest request, Long memberId, SundayMemberSessionDto memberSessionDto){
        SundayMember member = null;
        if(LongUtil.isNotNull(memberId)){
            member=super.getById(memberId);
            memberSessionDto=new SundayMemberSessionDto(member.getId(),  member.getWeixinUnionId(),member.getWeixinOpenId(),member.getStatus(),member.getUserType());
        }
        //logger.info("-----------插入session中的用户信息,openID==="+memberSessionDto.getWeixinOpenId());

        //先情况
        request.getSession().removeAttribute("member");
        request.getSession().setAttribute("member", memberSessionDto);
        return memberSessionDto;
    }

    /**
     * 清除用户session
     * @param request
     * @param memberId
     */
    public void clearMemberToSession(HttpServletRequest request, Long memberId){
        request.getSession().setAttribute("member", null);
    }
    /*****************************微信相关***************************/
    /**
     * 处理来至微信的用户信息。使用openId判断标识
     * @param unionId
     * @param openId
     * @param nickName
     * @param wxLogo
     */
    public SundayMemberSessionDto handleMemberInfo(String unionId,
                                        String openId,
                                        String nickName,
                                        String wxLogo){
        SundayMember member=null;
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        //使用openId标识用户(公众号)，使用unionId标识用户（服务号,需要绑定微信开放平台）

        //param.put("weixinUnionId",unionId);
        param.put("weixinOpenId",openId);
        List<SundayMember> oldMembers=super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            member=oldMembers.get(0);

        }else {
            member=new SundayMember();
            member.setNickName(nickName);
            member.setWeixinUnionId(unionId);
            member.setWeixinOpenId(openId);
            //保存微信头像
            String random= NumberUtil.generateNumber("ZB");
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/wxlogo/"+random+".jpg";
            ImageUtils.buildImg(savePath,wxLogo);
            //头像半链接
            member.setImage("/wxlogo/"+random+".jpg");

           //member.setIsGuanzhu(isGuanzhu);
           // member.setIsRegister(0);
            //member.setAbleVoteNumber(Finals.MEMBER_VOTE_NUMBER);
            //初始化个人信息
            member.setUserType(SundayCommonConstants.user_type_member);
            member.setParentId(0l);
           // 0欠费或冻结，1正常（默认）
            member.setStatus(SundayCommonConstants.user_status_zc);

            super.save(member);
        }
        SundayMemberSessionDto     memberDto=new SundayMemberSessionDto(member.getId(),  member.getWeixinUnionId(),member.getWeixinOpenId(),member.getStatus(),member.getUserType());

        logger.info("------处理来至微信请求-返回用户信息--"+memberDto.getId());
        return memberDto;
    }
    //通过openId查询用户是否存在

    /**
     * 通过weixinOpenId判断用户是否存在
     * @param openId
     * @return
     */
    public SundayMemberSessionDto checkOpenId(String openId){
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        param.put("weixinOpenId",openId);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNull(members))return null;
        SundayMember  member = members.get(0);
       // Integer isExistHigher = 1;

        return new SundayMemberSessionDto(member.getId(),  member.getWeixinUnionId(),member.getWeixinOpenId(),member.getStatus(),member.getUserType());
    }

   /* *//**
     * 员工注册（实际已经根据微信授权，生成了用户，这一步是完善个人信息）
     * @param request
     * @param memberId
     * @param mobile
     * @param code
     *//*
    public SundayMember register_employee(HttpServletRequest request,Long memberId,String mobile,String code){
        //检验验证码
        int reulct_code =codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_register);
        if(reulct_code!=0){
            throw new ErrorException("验证码错误");
        }
       //校验上级
        ZhongBaoContact contact = register_employee_check(mobile);
        SundayMember parent = super.getById(contact.getParentId());
        SundayMember member = new SundayMember();
        member.setId(memberId);
        member.setParentId(contact.getParentId());
        member.setNickName(contact.getNickName());
        member.setMobile(mobile);
        member.setTrade(parent.getTrade());
        member.setCareer(parent.getCareer());
        member.setProvinceId(parent.getProvinceId());
        member.setProvinceName(parent.getProvinceName());
        member.setCityId(parent.getCityId());
        member.setCityName(parent.getCityName());
        member.setDistrictId(parent.getDistrictId());
        member.setDistrictName(parent.getDistrictName());
        member.setCompany(parent.getCompany());
        member.setUserType(parent.getUserType());
        member.setStatus(SundayCommonConstants.user_status_zc);
        //member.setVersion(parent.getVersion());
        super.updateExceptEmpty(memberId,member);
        //重新把用户放入session中
        insertMemberToSession(request, memberId, null);
        return parent;

    }

    *//**
     * 校验员工是否存在
     * @param mobile
     *//*
    public ZhongBaoContact register_employee_check(String mobile){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("mobile",mobile);
        List<ZhongBaoContact> contacts=contactService.list(param);
        if(ListUtil.isNull(contacts)){
            throw new ErrorException("未找到您的手机号，请联系您的管理员");
        }else{
            ZhongBaoContact contact=contacts.get(0);
            if(LongUtil.isNotZreo(contact.getMemberId())){
                throw new ErrorException("该手机号已被注册");
            }
            return contact;
        }
    }*/

    /**
     * 获取用户详情
     * @param memberId
     * @return
     */
    public SundayMember getDetail(Long memberId){
        SundayMember member = null;
        if(LongUtil.isNotZreo(memberId)){
             member= super.getById(memberId);
            member.setTag(tagService.getTag(memberId,0l));
        }else{
            member=new SundayMember();
            member.setId(0l);
        }

        return member;
    }
    /********************2017年11月17日，员工员工*********/
    /**
     * 获取员工 或同事
     * @param request
     * @param memberId
     * @return
     */
    public  List<SundayMember> getEmployee(HttpServletRequest request,long memberId){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        SundayMember member= super.getById(memberId);
        if(LongUtil.isNotZreo(member.getParentId())){
            param.put("parentId",member.getParentId());
        }else{
            param.put("parentId",memberId);
        }
        param.put("parentId",memberId);
        param.put("userType",SundayCommonConstants.user_type_business);
        return super.list(param);
    }

    /**
     * 新增或修改员工。从已有的普通用户中选择
     * @param employeeId
     * @param nickName
     * @param mobile
     * @param parentId
     * @param trade
     * @param provinceId
     * @param provinceName
     * @param cityId
     * @param cityName
     * @param name1
     * @param name2
     * @param name3
     */
    public void saveEmployee(long employeeId,String nickName,String mobile,Long parentId,
                     //标签的信息
                     String trade, Long provinceId, String provinceName, Long cityId, String cityName, String name1, String name2, String name3
    ){

        SundayMember member =super.getById(employeeId);
        SundayMember parent = super.getById(parentId);
        member.setId(employeeId);
        member.setParentId(parentId);
        member.setNickName(nickName);
        member.setMobile(mobile);
        member.setTrade(parent.getTrade());
        member.setCareer(parent.getCareer());
        member.setProvinceId(parent.getProvinceId());
        member.setProvinceName(parent.getProvinceName());
        member.setCityId(parent.getCityId());
        member.setCityName(parent.getCityName());
        member.setDistrictId(parent.getDistrictId());
        member.setDistrictName(parent.getDistrictName());
        member.setCompany(parent.getCompany());
        member.setUserType(parent.getUserType());
        member.setStatus(SundayCommonConstants.user_status_zc);
        //member.setVersion(parent.getVersion());
        super.updateExceptEmpty(employeeId,member);
        //创建标签
        tagService.saveTag(employeeId, 0l,  trade,  provinceId,  provinceName,  cityId,  cityName,  name1,  name2,  name3);

    }

}
